package com.selftool.log;

import com.selftool.util.CommonUtil;

import javax.swing.*;
import java.math.BigDecimal;

/** 单例日志 */
//@Log4j
public class Logger {

    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Logger.class);
//    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Logger.class);
    /** 日志输出级别
     * lv0=all,lv1=info,lv2=warn,lv3=error
     * */
    private static Integer level = 3;
    private Logger(){}
    private static JTextArea textArea = null;
    public static void setBean(JTextArea bean){
        textArea = bean;
    }
    public static void write(Object data){
        try{
            if(textArea==null){
                return;
            }
            logger.info(data);
            setText(data.toString());
        }catch (Exception e){
            e.getStackTrace();
        }

    }
    public static void info(Object data){
        if(textArea==null){
            return;
        }
        if(level>1){
            return;
        }
        try{
            logger.info(data);
            setText(CommonUtil.initstr(data));
        }catch (Exception e){
            e.getStackTrace();
        }
    }
    /**
    * @Description: 增加主界面输出
    * @Param: [data]
    * @return: void
    * @Author: CYQ
    * @Date: 2024/2/26
    */
    private static void setText(String data){
        String text = textArea.getText();
        Integer max = 100000;
        Integer subLength = new BigDecimal(max).multiply(new BigDecimal(0.2)).intValue();
        //若超长,则删除前20%
        if(text!=null && text.length()>max){
            logger.info("当前控制台长度为"+text.length()+",正在执行控制台清理");
            text = text.substring(subLength,max);
        }
        textArea.setText(text+data+"\n");
        //定位光标至尾行
        textArea.setCaretPosition(textArea.getDocument().getLength());
    }
        /**
        * @Description: 输出error级日志
        * @Param: [data]
        * @return: void
        * @Author: CYQ
        * @Date: 2024/2/23
        */
        public static void error(String data){
            if(textArea==null){
                return;
            }
            if(level>=3){
                return;
            }
            try{
                logger.error(data);
                setText(data);
            }catch (Exception e){
                e.getStackTrace();
            }
        }

    public static void clearData() {
        if(textArea==null){
            return;
        }
        textArea.setText(null);
    }
}
